from tkinter import ttk
from threading import Thread
from config import *
from mini_tools.mytools import md5_encrypt
from sql import sqlseverDB
import tkinter.messagebox as messagebox
import tkinter as tk
import subprocess,json,time

class AdminLoginPage(tk.Frame):
    def __init__(self, parent,f000, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        #self.pack(expand=True, fill="both")
        self.f000=f000
        self.configure(bg='#34495e')  # 背景色
        self.ms = sqlseverDB('{SQL Server}', SQL_SERVER, 'SuMaiTongPol', SQL_USER, SQL_PWD)
        self.statusStr=tk.StringVar()
        self.statusStr.set('当前用户未登录')
        # 标题标签
        title_label = tk.Label(self, text="登录验证", font=("Helvetica", 24, "bold"), bg='#34495e', fg='white')
        title_label.pack(pady=20)

        # 账号标签和输入框
        username_label = tk.Label(self, text="用户名:", font=("Helvetica", 14), bg='#34495e', fg='white')
        username_label.pack(pady=5)
        self.username_entry = tk.Entry(self, font=("Helvetica", 14), width=30)
        self.username_entry.pack(pady=5)

        # 密码标签和输入框
        password_label = tk.Label(self, text="密码:", font=("Helvetica", 14), bg='#34495e', fg='white')
        password_label.pack(pady=5)
        self.password_entry = tk.Entry(self, font=("Helvetica", 14), width=30)
        self.password_entry.pack(pady=5)

        # 登录按钮
        self.login_btn = ttk.Button(self, text="登录", command=lambda :Thread(target=self.gtlogin).start())
        self.login_btn.pack(pady=20)
        tk.Label(self, textvariable=self.statusStr,fg='red').pack( pady=10)


    def gtlogin(self):
        username = self.username_entry.get().strip()
        password = self.password_entry.get().strip()

        # 在这里添加验证逻辑

        if not username or not password:
            messagebox.showinfo('提示','请输入账号密码')
            return
        self.login_btn.config(state=tk.DISABLED)
        self.statusStr.set('正在验证登录...')
        md5pwd=md5_encrypt(password)
        sqlstr='select utype from GTuser where uname=? and upwd=?'
        rs=self.ms.ExecQuery(sqlstr,(username,md5pwd))
        if len(rs)==0:
            self.login_btn.config(state=tk.NORMAL)
            print('账号密码错误')
            self.statusStr.set('账号密码错误')
            self.login_btn.config(state=tk.NORMAL)
            return
        else:
            utype=rs[0][0]
            with open('config.json','r',encoding='utf-8') as f:
                cobj=json.load(f)
            cobj['Uname']=username
            cobj['Upwd']=md5pwd
            with open('config.json','w',encoding='utf-8') as f:
                json.dump(cobj,f,ensure_ascii=False)

            print(f'{username}登录成功')
            self.statusStr.set(f'{username}登录成功')
            time.sleep(3)
            self.utype=utype
            self.pack_forget()
            self.f000.cgpb(utype)
            self.f000.pack()
        


